package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApBehaviorEntryimpl implements ApBehaviorEntryService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        //判断用户用什么登录
        //手机登录
        if (userId != null) {
            Query query = Query.query(Criteria.where("refId").is(userId).and("type").is(1));
            ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if (behaviorEntry == null) {

                apBehaviorEntry.setRefId(userId);
                apBehaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);
            }
            return behaviorEntry;
        }
        //设备登录
        if (equipmentId != null) {
            Query query = Query.query(Criteria.where("refId").is(equipmentId).and("type").is(0));
            ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
            ApBehaviorEntry behaviorEntry = mongoTemplate.findOne(query, ApBehaviorEntry.class);
            if (behaviorEntry == null) {

                apBehaviorEntry.setRefId(equipmentId);
                apBehaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
                apBehaviorEntry.setCreatedTime(new Date());
                mongoTemplate.save(apBehaviorEntry);

            }
            return behaviorEntry;
        }
        return null;
    }
}
